package org.lib.mysqlhello.security.self;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * AppUserDetailsService
 * @author ben
 * @date 2021-09-05 10:34:23 CST
 */
@Service
public class AppUserDetailsService implements UserDetailsService {

	@Autowired
	private AppUserDAO appUserDao;
	
	private Consumer<Object> cs = System.out::println;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		AppUser user = appUserDao.findByUsername(username);
		cs.accept("user 1=" + user);
		if (Objects.isNull(user)) {
			throw new UsernameNotFoundException("用户不存在");
		}
		
		// 权限集
		// 使用Spring Security的AuthorityUtils：默认支持 英文逗号分开的权限集
		user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRoles()));
		
		cs.accept("user 1=" + user);
		return user;
	}
	
	/**
	 * 权限转换：以 英文分号 分隔
	 * 未使用
	 * 可以取代前面的 AuthorityUtils.commaSeparatedStringToAuthorityList
	 * @author ben
	 * @date 2021-09-05 15:03:43 CST
	 * @param roles 角色列表字符串，以英文分号分隔
	 * @return
	 */
	private List<GrantedAuthority> generateAuthorities(final String roles) {
		List<GrantedAuthority> authorities = new ArrayList<>();
		final String sep = ";";
		String[] roleArr = roles.split(sep);
		Arrays.asList(roleArr).forEach(item -> {
			authorities.add(new SimpleGrantedAuthority(item));
		});
		return authorities;
	}

}
